package common

import (
	"encoding/json"
	"net/http"
	"regexp"

	"kingbloc.sso/user"

	"fmt"
	"github.com/garyburd/redigo/redis"
	"kingbloc.util/util"
	"strconv"
)

// get my infomation
func Myinfo(res http.ResponseWriter, req *http.Request) {

	var sweet map[string]interface{} = make(map[string]interface{})
	callback := req.FormValue("cb")
	if callback == "" {
		callback = "cb"
	}
	//my user info
	stat, userA := validateUserInfo(req)
	if !stat {
		sweet["state"] = 1
		all_info, _ := json.Marshal(sweet)
		util.WriteJSONP(res, callback+"("+string(all_info)+")")
		return
	}

	sweet["state"] = 0
	// 特殊字符替换
	reg := regexp.MustCompile(`"|'|<|\s`)
	callback = reg.ReplaceAllString(callback, "")
	if len(callback) > 10 {
		all_info, _ := json.Marshal(sweet)
		util.WriteJSONP(res, callback+"("+string(all_info)+")")
		return
	}

	userA.Password = ""
	sweet["userinfo"] = *userA
	sweet["state"] = 2
	all_info, _ := json.Marshal(sweet)
	if callback == "null" {
		util.WriteJSONP(res, string(all_info))
		return
	}

	util.WriteJSONP(res, callback+"("+string(all_info)+")")
	return
}

// 校验用户请求信息
func validateUserInfo(req *http.Request) (bool, *user.User) {
	tokenObj, _ := req.Cookie("SSOTOKEN")

	if tokenObj == nil {
		return false, nil
	}
	token := tokenObj.Value

	if token == "" {
		return false, nil
	}

	redisHost := conf.Get("redis", "host")
	redisPort := conf.Get("redis", "port")
	redisDB, _ := strconv.Atoi(conf.Get("redis", "db"))

	pc := util.GetRedisConn(redisHost+":"+redisPort, redisDB)
	if pc == nil {
		fmt.Println("error connection to database")
	}

	ref, _ := redis.String(pc.Do("GET", token))
	userA := new(user.User)

	if ref == "" {
		return false, nil
	} else {
		json.Unmarshal([]byte(ref), &userA)

	}

	if userA.Id > 0 {
		return true, userA
	}

	userA = byToken(token)
	//my user info
	if userA == nil {
		return false, nil
	}
	if userA.Id == 0 {
		return false, nil
	}

	return true, userA
}
